import winreg as reg
import os
import pathlib
import sys
from admin import run_as_admin


def add_to_context_menu(script_path, menu_text: str, icon_path=None):
    # 确保脚本路径存在
    script_path = str(script_path)
    icon_path = str(icon_path)
    if not os.path.exists(script_path):
        print(f"Script not found: {script_path}")
        return

    # 获取Python解释器路径
    # python_exe = os.path.join(os.environ['WINDIR'], 'py.exe')
    python_exe = sys.executable
    # print(python_exe,script_path)
    # return

    # 添加到桌面背景右键菜单
    key_path = rf"DesktopBackground\shell\{menu_text}"
    with reg.CreateKey(reg.HKEY_CLASSES_ROOT, key_path) as key:
        reg.SetValue(key, "", reg.REG_SZ, menu_text)
        if icon_path:
            reg.SetValue(key, "Icon", reg.REG_SZ, icon_path)

    key_path = rf"DesktopBackground\shell\{menu_text}\command"
    with reg.CreateKey(reg.HKEY_CLASSES_ROOT, key_path) as key:
        reg.SetValue(key, "", reg.REG_SZ, f'"{python_exe}" "{script_path}" "%V"')

    print("Context menu item added successfully.")


if __name__ == "__main__":
    MenuText = "移动窗口到此处"
    if run_as_admin() == False:
        exit()
    print("脚本运行需要安装第三方库，确认请按回车，拒绝安装请关闭本窗口！")
    input("是否继续？")
    os.system("pip install -r requirements.txt")
    print("运行环境准备完毕。")

    dir = pathlib.Path(__file__).parent
    script_name = "window.py"
    ico_name = "window.ico"
    add_to_context_menu(dir / script_name, MenuText, dir / ico_name)
    input(
        "菜单添加完毕，任意键关闭窗口！删除菜单，请用管理员权限运行“删除右键菜单.bat”"
    )
